<template>
  <div class="dashboard">
    <!-- 第一行：功能统计 -->
    <el-row :gutter="20" class="first-row" v-loading="loading">
      <el-col :span="8">
        <el-card class="feature-card" shadow="hover">
          <div class="card-header">
            <span class="card-title">功能统计</span>
          </div>
          <div class="feature-grid">
            <div class="feature-item" @click="navigateTo('/content/site')">
              <div class="feature-icon site-icon">
                <el-icon><OfficeBuilding /></el-icon>
              </div>
              <div class="feature-info">
                <div class="feature-name">站点管理</div>
                <div class="feature-count">{{ stats.siteCount }}</div>
              </div>
            </div>

            <div class="feature-item" @click="navigateTo('/content/channel')">
              <div class="feature-icon channel-icon">
                <el-icon><Menu /></el-icon>
              </div>
              <div class="feature-info">
                <div class="feature-name">栏目管理</div>
                <div class="feature-count">{{ stats.channelCount }}</div>
              </div>
            </div>

            <div class="feature-item" @click="navigateTo('/content/article')">
              <div class="feature-icon article-icon">
                <el-icon><Document /></el-icon>
              </div>
              <div class="feature-info">
                <div class="feature-name">文章管理</div>
                <div class="feature-count">{{ stats.articleCount }}</div>
              </div>
            </div>

            <div class="feature-item" @click="navigateTo('/system/model')">
              <div class="feature-icon model-icon">
                <el-icon><Grid /></el-icon>
              </div>
              <div class="feature-info">
                <div class="feature-name">模型管理</div>
                <div class="feature-count">{{ stats.modelCount || 0 }}</div>
              </div>
            </div>

            <div class="feature-item" @click="navigateTo('/content/attachment')">
              <div class="feature-icon attachment-icon">
                <el-icon><Paperclip /></el-icon>
              </div>
              <div class="feature-info">
                <div class="feature-name">附件管理</div>
                <div class="feature-count">{{ stats.attachmentCount }}</div>
              </div>
            </div>

            <div class="feature-item" @click="navigateTo('/system/theme')">
              <div class="feature-icon theme-icon">
                <el-icon><Brush /></el-icon>
              </div>
              <div class="feature-info">
                <div class="feature-name">主题管理</div>
                <div class="feature-count">{{ stats.themeCount || 0 }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="chart-card" shadow="hover">
          <div class="card-header">
            <span class="card-title">各类型数据统计</span>
          </div>
          <div class="chart-container">
            <div ref="barChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="chart-card" shadow="hover">
          <div class="card-header">
            <span class="card-title">用户比例</span>
          </div>
          <div class="chart-container">
            <div ref="pieChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行：趋势图和访客统计 -->
    <el-row :gutter="20" class="second-row">
      <el-col :span="16">
        <el-card class="chart-card" shadow="hover">
          <div class="card-header">
            <span class="card-title">数据趋势图</span>
            <div class="chart-legend">
              <span class="legend-item">
                <span class="legend-dot blue"></span>
                新增文章数
              </span>
              <span class="legend-item">
                <span class="legend-dot green"></span>
                新增用户数
              </span>
            </div>
          </div>
          <div class="chart-container large">
            <div ref="lineChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="visitor-card" shadow="hover">
          <div class="card-header">
            <span class="card-title">各状态项目数量</span>
          </div>
          <div class="visitor-stats">
            <div class="visitor-center">
              <div class="total-number">{{ stats.totalProjects || 18 }}</div>
              <div class="total-label">总数</div>
            </div>
            <div class="visitor-chart">
              <div ref="visitorPieChartRef" class="chart"></div>
            </div>
          </div>
          <div class="visitor-legend">
            <div class="legend-row">
              <span class="legend-item">
                <span class="legend-dot gray"></span>
                草稿
              </span>
              <span class="legend-item">
                <span class="legend-dot blue"></span>
                已提交
              </span>
            </div>
            <div class="legend-row">
              <span class="legend-item">
                <span class="legend-dot orange"></span>
                重新修订
              </span>
              <span class="legend-item">
                <span class="legend-dot yellow"></span>
                审核通过
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import * as dashboardApi from '@/api/dashboard'
import { useUserStore } from '@/stores/user'
import {
  Brush,
  Document,
  Grid,
  Menu,
  OfficeBuilding,
  Paperclip
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { nextTick, onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()

// 加载状态
const loading = ref(true)

// 统计数据
const stats = ref({
  siteCount: 0,
  channelCount: 0,
  articleCount: 0,
  attachmentCount: 0,
  modelCount: 0,
  themeCount: 0,
  totalProjects: 18,
})

// 图表引用
const barChartRef = ref<HTMLDivElement>()
const pieChartRef = ref<HTMLDivElement>()
const lineChartRef = ref<HTMLDivElement>()
const visitorPieChartRef = ref<HTMLDivElement>()

// 图表实例
let barChart: echarts.ECharts | null = null
let pieChart: echarts.ECharts | null = null
let lineChart: echarts.ECharts | null = null
let visitorPieChart: echarts.ECharts | null = null

// 导航到指定页面
const navigateTo = (path: string) => {
  router.push(path)
}

// 获取统计数据
const getStats = async () => {
  try {
    const response = await dashboardApi.getDashboardStats()
    if (response.code === 0) {
      stats.value = {
        ...response.data,
        modelCount: response.data.modelCount || 6,
        themeCount: response.data.themeCount || 3,
        totalProjects: 18,
      }
    } else {
      console.error('获取统计数据失败:', response.msg)
      // 使用默认数据作为备选方案
      stats.value = {
        siteCount: 0,
        channelCount: 0,
        articleCount: 0,
        attachmentCount: 0,
        modelCount: 6,
        themeCount: 3,
        totalProjects: 18,
      }
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
    // 使用默认数据作为备选方案
    stats.value = {
      siteCount: 0,
      channelCount: 0,
      articleCount: 0,
      attachmentCount: 0,
      modelCount: 6,
      themeCount: 3,
      totalProjects: 18,
    }
  }
}

// 初始化柱状图
const initBarChart = () => {
  if (!barChartRef.value) return

  barChart = echarts.init(barChartRef.value)
  const option = {
    color: ['#5470c6'],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['站点', '栏目', '文章'],
      axisLabel: {
        color: '#666'
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#666'
      }
    },
    series: [{
      data: [stats.value.siteCount, stats.value.channelCount, stats.value.articleCount],
      type: 'bar',
      barWidth: '60%',
      itemStyle: {
        borderRadius: [4, 4, 0, 0]
      }
    }]
  }
  barChart.setOption(option)
}

// 初始化饼图
const initPieChart = () => {
  if (!pieChartRef.value) return
  //在pieChartRef这个实例的dom元素的位置画出饼图
  pieChart = echarts.init(pieChartRef.value)
  const option = {
    color: ['#5470c6', '#91cc75', '#fac858', '#ee6666'],
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['50%', '50%'],
      data: [
        { value: 35, name: '管理员' },
        { value: 25, name: '编辑' },
        { value: 20, name: '作者' },
        { value: 20, name: '访客' }
      ],
      label: {
        show: false
      },
      labelLine: {
        show: false
      }
    }]
  }
  //通过option画出饼图
  pieChart.setOption(option)
}

// 查看文章
const viewArticle = (id: number) => {
  router.push(`/content/article/${id}`)
}

// 获取状态类型
const getStatusType = (status: number) => {
  const statusMap: Record<number, string> = {
    0: 'success',
    1: 'info',
    5: 'warning',
    10: 'info',
    20: 'danger',
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '已发布',
    1: '已归档',
    5: '待发布',
    10: '草稿',
    20: '已删除',
  }
  return statusMap[status] || '未知'
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 初始化折线图
const initLineChart = () => {
  if (!lineChartRef.value) return

  lineChart = echarts.init(lineChartRef.value)
  const option = {
    color: ['#5470c6', '#91cc75'],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      axisLabel: {
        color: '#666'
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#666'
      }
    },
    series: [
      {
        name: '新增文章数',
        type: 'line',
        smooth: true,
        data: [8, 12, 15, 18, 22, 25, 28, 32, 35, 30, 28, 25]
      },
      {
        name: '新增用户数',
        type: 'line',
        smooth: true,
        data: [5, 8, 10, 12, 15, 18, 20, 22, 25, 20, 18, 15]
      }
    ]
  }
  lineChart.setOption(option)
}

// 初始化访客饼图
const initVisitorPieChart = () => {
  if (!visitorPieChartRef.value) return

  visitorPieChart = echarts.init(visitorPieChartRef.value)
  const option = {
    color: ['#909399', '#5470c6', '#fac858', '#f9d71c'],
    series: [{
      type: 'pie',
      radius: ['60%', '80%'],
      center: ['50%', '50%'],
      data: [
        { value: 5, name: '草稿' },
        { value: 8, name: '已提交' },
        { value: 2, name: '重新修订' },
        { value: 3, name: '审核通过' }
      ],
      label: {
        show: false
      },
      labelLine: {
        show: false
      }
    }]
  }
  visitorPieChart.setOption(option)
}

// 初始化所有图表
const initCharts = async () => {
  await nextTick()
  initBarChart()
  initPieChart()
  initLineChart()
  initVisitorPieChart()
}

onMounted(async () => {
  loading.value = true
  try {
    // 获取数据
    await getStats()
    // 初始化图表
    await initCharts()
  } catch (error) {
    console.error('初始化仪表盘数据失败:', error)
  } finally {
    loading.value = false
  }
})

onUnmounted(() => {
  // 清理图表实例
  if (barChart) {
    barChart.dispose()//销毁图表
    barChart = null//清空引用
  }
  if (pieChart) {
    pieChart.dispose()
    pieChart = null
  }
  if (lineChart) {
    lineChart.dispose()
    lineChart = null
  }
  if (visitorPieChart) {
    visitorPieChart.dispose()
    visitorPieChart = null
  }
})
</script>

<style scoped lang="scss">
.dashboard {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);

  .first-row {
    margin-bottom: 20px;
  }

  .second-row {
    margin-bottom: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .card-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }

    .chart-legend {
      display: flex;
      gap: 20px;

      .legend-item {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #606266;

        .legend-dot {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          margin-right: 6px;

          &.blue {
            background-color: #5470c6;
          }

          &.green {
            background-color: #91cc75;
          }

          &.gray {
            background-color: #909399;
          }

          &.orange {
            background-color: #fac858;
          }

          &.yellow {
            background-color: #f9d71c;
          }
        }
      }
    }
  }

  .feature-card {
    height: 100%;

    .feature-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20px;

      .feature-item {
        display: flex;
        align-items: center;
        padding: 15px;
        border-radius: 8px;
        background-color: #f8f9fa;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          background-color: #e9ecef;
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .feature-icon {
          width: 40px;
          height: 40px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 12px;
          font-size: 18px;
          color: white;

          &.site-icon {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }

          &.channel-icon {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }

          &.article-icon {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }

          &.model-icon {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
          }

          &.attachment-icon {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }

          &.theme-icon {
            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
          }
        }

        .feature-info {
          .feature-name {
            font-size: 14px;
            color: #606266;
            margin-bottom: 4px;
          }

          .feature-count {
            font-size: 20px;
            font-weight: 600;
            color: #303133;
          }
        }
      }
    }
  }

  .chart-card {
    height: 100%;

    .chart-container {
      .chart {
        width: 100%;
        height: 200px;
      }

      &.large .chart {
        height: 300px;
      }
    }
  }

  .visitor-card {
    height: 100%;

    .visitor-stats {
      position: relative;
      height: 200px;

      .visitor-center {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        text-align: center;
        z-index: 10;

        .total-number {
          font-size: 32px;
          font-weight: 600;
          color: #303133;
          line-height: 1;
        }

        .total-label {
          font-size: 12px;
          color: #909399;
          margin-top: 4px;
        }
      }

      .visitor-chart {
        width: 100%;
        height: 100%;

        .chart {
          width: 100%;
          height: 100%;
        }
      }
    }

    .visitor-legend {
      margin-top: 20px;

      .legend-row {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;

        .legend-item {
          display: flex;
          align-items: center;
          font-size: 12px;
          color: #606266;

          .legend-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 6px;

            &.gray {
              background-color: #909399;
            }

            &.blue {
              background-color: #5470c6;
            }

            &.orange {
              background-color: #fac858;
            }

            &.yellow {
              background-color: #f9d71c;
            }
          }
        }
      }
    }
  }
}
</style>
